package yhao.infra.web.common.enumsmap;

import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import yhao.infra.web.common.enumsmap.annotation.config.EnableSelectable;

/**
 * @author wuweipeng
 * @author liwan
 * @date 2021/7/20 9:32
 */
public class OnSelectableCondition extends SpringBootCondition {
	@Override
	public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
		Class clazz = deduceMainApplicationClass();
		final EnableSelectable annotation = (EnableSelectable) clazz.getAnnotation(EnableSelectable.class);
		if(annotation != null){
			return new ConditionOutcome(true,"");
		}
		return new ConditionOutcome(false,"");
	}

	private Class<?> deduceMainApplicationClass() {
		try {
			StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
			for (StackTraceElement stackTraceElement : stackTrace) {
				if ("main".equals(stackTraceElement.getMethodName())) {
					return Class.forName(stackTraceElement.getClassName());
				}
			}
		}
		catch (ClassNotFoundException ex) {
			// Swallow and continue
		}
		return null;
	}
}
